package std

import (
	"crypto/tls"
	"crypto/x509"
	"database/sql"
	"fmt"
	"os"
	"path"

	"rdbmsx/config"

	"github.com/ClickHouse/clickhouse-go/v2"
)

func ConnectSSL() error {
	cwd, err := os.Getwd()
	if err != nil {
		return err
	}

	t := &tls.Config{}

	caCert, err := os.ReadFile(path.Join(cwd, "../../tests/resources/CAroot.crt"))
	if err != nil {
		return err
	}

	caCertPool := x509.NewCertPool()

	successful := caCertPool.AppendCertsFromPEM(caCert)
	if !successful {
		return err
	}

	t.RootCAs = caCertPool

	option := config.ClickHouseConfig.Option(func(options *clickhouse.Options) {
		options.TLS = t
	})

	conn := clickhouse.OpenDB(&option)

	return conn.Ping()
}

func ConnectDSNSSL() error {
	conn, err := sql.Open("clickhouse", fmt.Sprintf("https://%s?secure=true&skip_verify=true&username=%s&password=%s", config.ClickHouseHost, config.ClickHouseUser, config.ClickHousePassword))
	if err != nil {
		return err
	}

	return conn.Ping()
}
